/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.UserList;
import com.tzinfo.tzb.util.TzbCommonData;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.util.ResFinder;

public class TzbMyFansActivity extends TzbBaseActivity implements
		IXListViewListener {
	// 参数
	public boolean isFans = false;
	private int fanstype;

	// 适配器
	private MyImageAdapter imageAdapter;

	// 数据
	private UserList userList = null;

	// UI组件
	private YXWXListView listView;
	private RelativeLayout layout_no_listdata;
	private TextView text_no_listdata;
	private TextView text_title;

	// 其他
	public static TzbMyFansActivity activity;
	private Handler mHandler;
	private int page = 1; // 页码
	private int pagesize = 10; // 每页条数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		activity = this;
		setContentView(ResFinder.getR(this, "R.layout.tzb_ac_main_my_fans"));
		initParameter();
		initUI();
		initData();
		listView.setSelection(0);
	}

	private void initParameter() {
		mHandler = new Handler();
		isFans = this.getIntent().getBooleanExtra("isFans", false);
	}

	private void initUI() {
		listView = (YXWXListView) ResFinder
				.findViewById(this, "R.id.xListView");
		layout_no_listdata = (RelativeLayout) ResFinder.findViewById(this,
				"R.id.layout_no_listdata");
		text_title = (TextView) ResFinder.findViewById(this, "R.id.text_title");
		text_no_listdata = (TextView) ResFinder.findViewById(this,
				"R.id.text_no_listdata");
		if (isFans) {
			text_no_listdata.setText("您还没有粉丝");
		} else {
			text_no_listdata.setText("您还没有关注人");
		}

		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(this);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				String username = userList.getData().get((int) l).getUsername();
				Intent intent = new Intent(TzbMyFansActivity.this,
						TzbUserInfoActivity.class);
				intent.putExtra("username", username);
				startActivity(intent);
			}
		});
	}

	public void initData() {
		requestInfo();
	}

	private void initListView() {
		// 初始化data
		if (userList == null || userList.getData().size() == 0) {
			layout_no_listdata.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		} else {
			if (imageAdapter == null) {
				imageAdapter = new MyImageAdapter();
				listView.setAdapter(imageAdapter);
			} else {
				imageAdapter.notifyDataSetChanged();
			}
		}
	}

	// 重载，默认请求新数据
	private void requestInfo() {
		requestInfo(TzbCommonData.NOPULL_LOAD);
	}

	private void requestInfo(int type) {
		dialog.show();
		final int type2 = type;
		if (type == TzbCommonData.NOPULL_LOAD) {
			showProgressBar();
		}
		if (isFans) {
			fanstype = 2;
		} else {
			fanstype = 1;
		}
		String url = ResFinder.getResString(this,
				"R.string.tzb_url_UserFansList")
				+ "?sessionid="
				+ TztData.userInfo.getData().getSessionID()
				+ "&type="
				+ fanstype + "&Page=" + page + "&Pagesize=" + pagesize;
		OutLog.LogE("url", url + "");
		GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<UserList>() {
				}.getType();

				UserList temp = gson.fromJson(arg0, type);
				dialog.dismiss();
				if (temp != null && temp.isSuccess()) {
					layout_no_listdata.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
					if (type2 == TzbCommonData.PULL_LOAD_MORE) {
						for (int i = 0; i < temp.getData().size(); i++) {
							userList.getData().add(temp.getData().get(i));
						}
						if (temp.getData().size() < 10) {
							listView.setPullLoadEnable(false);
							Toast.makeText(TzbMyFansActivity.this, "已经是最后一页！",
									Toast.LENGTH_LONG).show();
						}
					} else if (type2 == TzbCommonData.PULL_REFLASH
							|| type2 == TzbCommonData.NOPULL_LOAD) {
						if (temp.getData().size() == 0) {
							layout_no_listdata.setVisibility(View.VISIBLE);
							listView.setVisibility(View.GONE);
						}
						userList = temp;
						if (userList.getData().size() < 10) {
							listView.setPullLoadEnable(false);
						} else {
							listView.setPullLoadEnable(true);
						}
					}
					initListView();
					onLoadFinish();
				} else {
					if (userList != null) {
						Toast.makeText(TzbMyFansActivity.this,
								userList.getMsg(), Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(TzbMyFansActivity.this, "数据加载失败，请检查网络！",
								Toast.LENGTH_LONG).show();
					}
					layout_no_listdata.setVisibility(View.VISIBLE);
					listView.setVisibility(View.GONE);
				}
				removeProgressBar();
			}
		});
	}

	// onclick切换tab

	private void onLoadFinish() {
		listView.stopRefresh();
		listView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		listView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page = 1;
				requestInfo(TzbCommonData.PULL_REFLASH);
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page++;
				requestInfo(TzbCommonData.PULL_LOAD_MORE);
			}
		}, 2000);
	}

	class MyImageAdapter extends BaseAdapter {
		private LayoutInflater inflater;

		public MyImageAdapter() {
			context = TzbMyFansActivity.this;
			imageLoader = ImageLoader.getInstance();
			inflater = (LayoutInflater) context
					.getSystemService("layout_inflater");
			options = (new DisplayImageOptions.Builder())
					.showImageOnLoading(
							ResFinder.getR(context, "R.drawable.ic_empty"))
					.showImageForEmptyUri(
							ResFinder.getR(context, "R.drawable.ic_empty"))
					.showImageOnFail(
							ResFinder.getR(context, "R.drawable.ic_empty"))
					.cacheInMemory(true).cacheOnDisc(true)
					.bitmapConfig(android.graphics.Bitmap.Config.RGB_565)
					.build();
		}

		public int getCount() {
			return userList.getData().size();
		}

		public Object getItem(int position) {
			return userList.getData().get(position);
		}

		public long getItemId(int position) {
			return (long) position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = inflater.inflate(ResFinder.getR(
						TzbMyFansActivity.this, "R.layout.tzb_item_userinfo"),
						parent, false);
			ImageView imageView = (ImageView) ResFinder.findViewById(
					convertView, "R.id.list_item_image");
			imageLoader.displayImage(userList.getData().get(position)
					.getAvatar(), imageView, options);
			TextView list_item_user = (TextView) ResFinder.findViewById(
					convertView, "R.id.list_item_user");

			String name = userList.getData().get(position).getNetname();
			if (name == null || "".equals(name.trim())) {
				name = userList.getData().get(position).getUsername();
			}
			list_item_user.setText(name);
			// 注册时间
			TextView list_item_time = (TextView) ResFinder.findViewById(
					convertView, "R.id.list_item_time");
			String sTime = YXWDateUtil.getTimeInterval(
					userList.getData().get(position).getRegdate(),
					"MM/dd/yyyy HH:mm:ss");
			list_item_time.setText(sTime + "");
			TextView list_item_sex = (TextView) ResFinder.findViewById(
					convertView, "R.id.list_item_sex");
			TextView list_item_yearsold = (TextView) ResFinder.findViewById(
					convertView, "R.id.list_item_yearsold");
			String bbyearold = YXWDateUtil.getBabyTimeInterval(
					userList.getData().get(position).getBbbirthday(),
					"yyyy-MM-dd HH:mm:ss");
			list_item_yearsold.setText(bbyearold);
			if ("".equals(userList.getData().get(position).getBbsex())) {
				list_item_sex.setText("无宝宝");
				list_item_yearsold.setText("");
			} else {
				list_item_sex.setText(userList.getData().get(position).getBbsex());
				if("男宝宝".equals(userList.getData().get(position).getBbsex().trim())){
					list_item_sex.setSelected(true);
					list_item_yearsold.setSelected(true);
				}else{
					list_item_sex.setSelected(false);
					list_item_yearsold.setSelected(false);
				}
			}
			TextView list_item_credits = (TextView) ResFinder.findViewById(
					convertView, "R.id.list_item_credits");
			list_item_credits.setText(userList.getData().get(position)
					.getCredits()
					+ "");

			return convertView;
		}

		private Context context;
		private DisplayImageOptions options;

		protected ImageLoader imageLoader;
	}
}
